/*************************************************************************
	> File Name: client.c
	> Author: anhao
	> Mail: wzzlyzdn@qq.com 
	> Created Time: 2020年08月25日 星期二 15时58分23秒
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<arpa/inet.h>
#include<pthread.h>

#define THREAD_NUM 1

const int error_timer = 3;

int create_client_socket(int timer, int * cli_socket);
int connect_serv(int timer, int cli_socket, char *argv);
void *client_recv(void *arg);

int main(int argc, char **argv)
{
    int cli_socket = -1;
    pthread_t thread[THREAD_NUM];
    
    if(-1 == create_client_socket(error_timer,&cli_socket))
        return -1;
    if(-1 == connect_serv(error_timer, cli_socket, argv[1]))
        return -1;
    
    long arg = (long)cli_socket;
    pthread_create(thread, NULL, client_recv, (void *)arg);
    pthread_detach(thread[0]);
    
    char buf0[100] = {0};
    while(1)
    {   
        scanf("%s",buf0);
        buf0[sizeof(buf0)] = '\0';
        send(cli_socket, buf0, sizeof(buf0), 0);
        if(strncmp(buf0, "quit", 4) == 0)
        {
            printf("登出！\n");
            break;
        }
    }
    close(cli_socket);
    return 0;
}

int create_client_socket(int timer, int * cli_socket)
{
    while(timer--)
    {
        *cli_socket = socket(AF_INET, SOCK_STREAM, 0);
        if(cli_socket > 0)
        {
            printf("client_socket 创建成功！\n");
            break;
        }
        else
        {
            printf("client_socket 创建失败！\n正在第%2d次重试！请稍后...\n", error_timer - timer);
            if(timer == 0)
            {
                perror("请求超时！\n");
                return -1;
            }
        }
    }
    return 0;
}

int connect_serv(int timer, int cli_socket, char *argv)
{
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(struct sockaddr_in));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = 8080;
    serv_addr.sin_addr.s_addr = inet_addr(argv);

    while(timer--)
    {
        int rev = -1;
        rev = connect(cli_socket, (struct sockaddr *)(&serv_addr), sizeof(struct sockaddr));
        if(rev >= 0)
        {
            printf("连接服务器成功！\n");
            break;
        }
        else 
        {
            printf("连接服务器失败！\n正在第%2d次重试！请稍后...\n", error_timer - timer);
            usleep(1000);
            if(timer == 0)
            {
                perror("请求超时！\n");
                return -1;
            }
        }
    }
    return 0;
}

void *client_recv(void *arg)
{
    long cli = (long)arg;
    int cli_socket = (int)cli;
    char buf0[100] = {0};
    while(1)
    {
        int ret = recv(cli_socket, buf0, 100, 0);
        buf0[ret] = '\0';
        printf("%s\n", buf0);
    }

    pthread_exit(NULL);
}
